package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApAuthorMapper;
import com.heima.article.service.ApAuthorService;
import com.heima.common.exception.CustException;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ApAuthorServiceImpl extends ServiceImpl<ApAuthorMapper, ApAuthor> implements ApAuthorService {
    @Autowired
    private ApAuthorMapper apAuthorMapper;

    //根据ApUser id查询作者信息
    @Override
    public ResponseResult findByUserId(Integer id) {
        //非空判断
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据user_id查询作者信息
        LambdaQueryWrapper<ApAuthor> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ApAuthor::getUserId,id);
        ApAuthor apAuthor = apAuthorMapper.selectOne(wrapper);
        //判断
        if (apAuthor == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //存在数据,封装并返回
        return ResponseResult.okResult(apAuthor);
    }

    //保存作者信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult insert(ApAuthor apAuthor) {
        //非空判断
        if (apAuthor == null || apAuthor.getUserId() == null || StringUtils.isBlank(apAuthor.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据userId查询是否重复
        LambdaQueryWrapper<ApAuthor> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(ApAuthor::getUserId, apAuthor.getUserId());
        List<ApAuthor> apAuthors = apAuthorMapper.selectList(wrapper);
        //判断
        if (apAuthors.size() != 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //判断是否有WmUserId
        if (apAuthor.getWmUserId() != null) {
            //查询WmUserId是否重复
            LambdaQueryWrapper<ApAuthor> wrapper2 = Wrappers.lambdaQuery();
            wrapper2.eq(ApAuthor::getWmUserId, apAuthor.getWmUserId());
            List<ApAuthor> apAuthors2 = apAuthorMapper.selectList(wrapper);
            //判断
            if (apAuthors2.size() != 0) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
            }
        }
        //插入数据
        if (apAuthorMapper.insert(apAuthor) != 1) {
            //插入失败
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult();
    }
}
